# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.utils import simplejson
from loginzauth.middleware import SESSION_USER_VARNAME
from loginzauth.models import LoginzaUser, Identity
from urllib import urlencode
import urllib2


REDIRECT_AFTER_LOGIN = getattr(settings, 'LOGINZA_REDIRECT_AFTER_LOGIN', '/')
REDIRECT_AFTER_LOGOUT = getattr(settings, 'LOGINZA_REDIRECT_AFTER_LOGOUT', '/')


def logout(request):
    del request.session[SESSION_USER_VARNAME]
    return HttpResponseRedirect(REDIRECT_AFTER_LOGOUT)

def login(request):
    return_to = request.GET.get('return_to', REDIRECT_AFTER_LOGIN)
    return TemplateResponse(request, 'login.html', {
        'token_url': 'http://%s%s?%s' % (
            request.get_host(),
            reverse(loginza_return),
            urlencode({'return_to': return_to}),
        )
    })

def loginza_return(request):
    if request.method != 'POST':
        return HttpResponse('Invalid request')

    url = 'http://loginza.ru/api/authinfo?token=%s' % request.POST.get('token', '')
    content = urllib2.urlopen(url).read()
    data = simplejson.loads(content)

    if 'error_type' in data:
        return HttpResponse(content)

    identity, created = Identity.objects.get_or_create(identity=data.pop('identity'))
    identity.set_data(data)
    identity.save()

    if created:
        loginza_user = LoginzaUser.objects.create()
        loginza_user.identities.add(identity)
        loginza_user.save()
    else:
        try:
            loginza_user = LoginzaUser.objects.get(identities=identity)
        except LoginzaUser.DoesNotExist:
            return HttpResponse('Invalid user: %s' % repr(identity))

    if not loginza_user.name:
        loginza_user.name = identity.get_name()
        loginza_user.save()

    request.session[SESSION_USER_VARNAME] = loginza_user.pk

    return_to = request.GET.get('return_to', REDIRECT_AFTER_LOGIN)
    return HttpResponseRedirect(return_to)
